"""
    Author:
    Date: 2019-12-15

    Api接口的实现文件
"""

import random

from django.conf import settings

from . import helpers
from entities.consts import *
from entities.err import *
from entities import bank_mgr
from entities import redis_mgr
from entities import sms_mgr
from entities import user_mgr
from entities import vchat_api_mgr
from utils import util
from utils import haibao_util
from utils.log import Log

# -----------------------------------------------------------
# Part of MpPay
# -----------------------------------------------------------

def api_user_info(request, uid):
    """ 查询用户基本信息 """
    if not uid.isdigit():
        return ERROR_USER_NOT_EXIST, None

    user = user_mgr.get_user_detail(uid)
    if user is None:
        user = user_mgr.get_user_detail_by_mobile(uid)
        if user is None:
            return ERROR_USER_NOT_EXIST, None

    # 缓存用户的请求IP
    client_ip = util.get_request_real_ip(request)[0]
    key = redis_mgr.KEY_USER_PAY_IP % int(user['uid'])
    redis_mgr.cache_string(key, client_ip, 7*24*3600)

    data = {
        'uid': user['uid'],
        'avatar': user['avatar'],
        'nickname': user['nickname'],
    }
    return ERROR_NO_ERROR, data

def api_get_hsq_mp_prepay_info(request, uid, amount):
    """ 获取慧收钱的公众号预支付信息 """
    # 检测参数
    user = user_mgr.get_user_detail(uid)
    if user is None:
        return ERROR_USER_NOT_EXIST, None

    if amount <= 0:
        Log.error(f'[HSQ] mp pay failed for invalid amount: uid={uid}, amount={amount}')
        return ERROR_INVALID_PAY_AMOUNT, None

    # 提取其他参数
    appid = settings.WX_MP_APPID
    if not appid:
        Log.error(f'[HSQ] mp pay failed for lack appid: uid={uid}, amount={amount}')
        return ERROR_LACK_APPID, None

    openid = helpers.get_request_openid(request)
    if not openid:
        Log.error(f'[HSQ] mp pay failed for lack openid: uid={uid}, amount={amount}')
        return ERROR_LACK_OPENID, None

    client_ip = util.get_request_real_ip(request)[0]

    # 请求接口
    result = vchat_api_mgr.prepay_with_hsq_mp(uid, amount, appid, openid, client_ip)
    if result is None:
        Log.error(f'[HSQ] mp pay failed for result is None: uid={uid}, amount={amount}')
        return ERROR_PAY_FAILED, None
    Log.info(f'[HSQ] mp pay result: {result}')

    # 构造返回给客户端的数据
    data = {
        'order_status': result.get('orderStatus', ''),
        'qr_code': result.get('qrCode', ''),
        'resp_code': result.get('respCode', ''),
        'resp_msg': result.get('respMsg', ''),
    }
    return ERROR_NO_ERROR, data


# -----------------------------------------------------------
# Part of Withdraw
# -----------------------------------------------------------

def api_fetch_smscode(request, mobile):
    """ 获取用户的提现信息 """
    # 检测参数
    if not mobile:
        return ERROR_INVALID_MOBILE, None

    # 发送验证码
    sms_code = ''.join([random.choice('0123456789') for _ in range(4)])
    success = sms_mgr.send_sms_code(mobile, sms_code)
    if not success:
        return ERROR_SYSTEM_ERROR, None

    # 回应客户端
    data = {}
    return ERROR_NO_ERROR, data

def api_fetch_token(request, mobile, sms_code):
    """ 获取AccessToken """
    # 检测参数
    if not mobile:
        return ERROR_INVALID_MOBILE, None

    if not sms_code:
        return ERROR_INVALID_SMS_CODE, None

    # 检测验证码是否合法
    if not sms_mgr.is_valid_sms_code(mobile, sms_code):
        return ERROR_INVALID_SMS_CODE, None

    # 获取用户信息
    user = user_mgr.get_user_detail_by_mobile(mobile)
    if user is None:
        return ERROR_USER_NOT_EXIST, None

    data = {
        'access_token': user['token'],
    }
    return ERROR_NO_ERROR, data

def api_withdraw_user_info(request, mobile):
    """ 获取用户的提现信息 """
    if not mobile:
        return ERROR_INVALID_MOBILE, None

    # 查找用户基本信息
    user = user_mgr.get_user_detail_by_mobile(mobile)
    if not user:
        return ERROR_USER_EXIST, None

    # 获取用户的银行卡信息
    uid = user['uid']
    bank = bank_mgr.get_user_bank_info(mobile)
    red_gem = user['red_gem']
    green_gem = user['green_gem']

    # 构造返回给用户的参数
    data = {
        'authenticated': 1 if user_mgr.is_authorised_broadcaster(uid) else 0,
        'red_gem': red_gem,
        'withdraw_amount_for_red_gem': int(red_gem/100),
        'green_gem': green_gem,
        'withdraw_amount_for_green_gem': int(green_gem / 100),
        'bank_name': bank['bank_name'] if bank else '',
        'bank_card_tail_number': bank['bank_card_number'][-4:] if bank else '',
    }
    return ERROR_NO_ERROR, data

# def api_withdraw_person_auth(request, mobile, sms_code, real_name, cert_no, bank_name, bank_card_number, bank_address, bank_branch):
#     """ 信息认证 """
#     # 验证参数合法性
#     if not mobile:
#         return ERROR_INVALID_MOBILE, None
#
#     if not sms_code:
#         return ERROR_INVALID_SMS_CODE, None
#
#     if not real_name:
#         return ERROR_INVALID_REAL_NAME, None
#
#     if not cert_no:
#         return ERROR_INVALID_CERT_NO, None
#
#     if not bank_name:
#         return ERROR_INVALID_BANK_NAME, None
#
#     if not bank_card_number:
#         return ERROR_INVALID_BANK_CARD_NUMBER, None
#
#     if not bank_address:
#         return ERROR_INVALID_BANK_ADDRESS, None
#
#     if not bank_branch:
#         return ERROR_INVALID_BANK_BRANCH, None
#
#     # 检测验证码是否合法
#     if not sms_mgr.is_valid_sms_code(mobile, sms_code):
#         return ERROR_INVALID_SMS_CODE, None
#
#     # 查找用户基本信息
#     user = user_mgr.get_user_detail_by_mobile(mobile)
#     if not user:
#         return ERROR_USER_EXIST, None
#
#     # 调用API Server的接口，验证用户提交的信息
#     code, msg, data = haibao_util.save_user_withdraw_auth_info(mobile, real_name, cert_no, bank_name, bank_card_number, bank_address, bank_branch)
#     if data is None:
#         return ERROR_SYSTEM_ERROR, None
#
#     # # 保存用户的银行信息
#     # uid = user['id']
#     # data = bank_mgr.save_user_bank_info(uid, mobile, real_name, cert_no, bank_name, bank_address, bank_branch, bank_card_number)
#     # if data is None:
#     #     return ERROR_SYSTEM_ERROR, None
#
#     return ERROR_NO_ERROR, data

def api_withdraw_fee(request, mobile, amount, gem_type):
    """ 计算提现费用 """
    # 检测用户所传递的参数是否合法
    if not mobile:
        return ERROR_INVALID_MOBILE, None

    if amount <= 0:
        return ERROR_INVALID_WITHDRAW_AMOUNT, None

    if gem_type not in [GEM_OF_RED, GEM_OF_GREEN]:
        return ERROR_INVALID_GEM_TYPE, None

    # 判断用户是否存在
    user = user_mgr.get_user_detail_by_mobile(mobile)
    if not user:
        return ERROR_USER_EXIST, None

    # 计算提现费用
    fee_ratio = 0.07
    fee = amount * fee_ratio
    transfer_amount = amount - fee
    data = {
        'amount': f'{amount:.02f}',
        'fee': f'{fee:.02f}',
        'transfer_amount': f'{transfer_amount:.02f}',
    }
    return ERROR_NO_ERROR, data

# def api_withdraw_submit(request, mobile, amount, gem_type):
#     """ 提现接口 """
#     # 检测用户所传递的参数是否合法
#     if not mobile:
#         return ERROR_INVALID_MOBILE, None
#
#     if amount <= 0:
#         return ERROR_INVALID_WITHDRAW_AMOUNT, None
#
#     # 查找用户基本信息
#     user = user_mgr.get_user_detail_by_mobile(mobile)
#     if not user:
#         return ERROR_USER_EXIST, None
#
#     # 检测用户身上是否有足够的宝石
#     if gem_type == GEM_OF_RED:
#         need_red_gem = amount * 100
#         if need_red_gem > user['red_gem']:
#             return ERROR_LACK_RED_GEM, None
#     elif gem_type == GEM_OF_GREEN:
#         need_green_gem = amount * 100
#         if need_green_gem > user['green_gem']:
#             return ERROR_LACK_GREEN_GEM, None
#     else:
#         return ERROR_INVALID_GEM_TYPE, None
#
#     # 调用API Server的接口提现
#     code, msg, data = haibao_util.user_submit_withdraw(mobile, amount, gem_type)
#     if data is None:
#         return ERROR_SYSTEM_ERROR, None
#
#     return ERROR_NO_ERROR, data

# # -----------------------------------------------------------
# # Part of 实名认证
# # -----------------------------------------------------------
#
# def api_user_auth_info(request, uid):
#     """ 查询用户审核信息 """
#     if not uid.isdigit():
#         return ERROR_USER_NOT_EXIST, None
#
#     user = user_mgr.get_user_detail(uid)
#     if user is None:
#         user = user_mgr.get_user_detail_by_mobile(uid)
#         if user is None:
#             return ERROR_USER_NOT_EXIST, None
#
#     # # 缓存用户的请求IP
#     # client_ip = util.get_request_real_ip(request)[0]
#     # key = redis_mgr.KEY_USER_PAY_IP % int(user['uid'])
#     # redis_mgr.cache_string(key, client_ip, 7*24*3600)
#
#     # 查询审核状态
#     uid = user['uid']
#     status = 0
#     auth_info = user_mgr.get_user_auth_detail(uid)
#     if auth_info is not None:
#         status = auth_info['status']
#
#     data = {
#         'uid': user['uid'],
#         'avatar': user['avatar'],
#         'nickname': user['nickname'],
#         'status': status,
#     }
#     return ERROR_NO_ERROR, data


if __name__ == '__main__':
    print('ok')
